package com.ruben.simplescaffold.controller;

import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ClassUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ruben.simplescaffold.pojo.common.Result;
import com.ruben.simplescaffold.service.OssService;
import com.ruben.simplescaffold.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * 文件上传
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/5/20 0020 19:24
 */
@Slf4j
@RestController
public class UploadController {

    @Resource
    private OssService ossService;

    @PostMapping("upload")
    public Result projectPictureUpload(MultipartFile file) {
        //将图片上传到服务器
        if (file.isEmpty()) {
            return Result.error("项目图片不能为空");
        }
        //原始文件名
        String originalFilename = Opt.ofNullable(file.getOriginalFilename()).orElseGet(file::getName);
        //文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //图片名称为uuid+图片后缀防止冲突
        String fileName = IdWorker.getTimeId() + "." + suffix;
        // 项目文件保存路径
        String filePath = "";
        //获取项目classes/static的地址
        filePath = Objects.requireNonNull(ClassUtil.getClassLoader().getResource("static")).getPath() + "/upload/img/";
        try {
            // 写入文件
            Boolean writePictureTarget = FileUtils.saveFile(file.getBytes(), filePath, fileName);
            // 开发环境中写一份在本地
            Boolean writePictureProject = FileUtils.saveFile(file.getBytes(), System.getProperty("user.dir") + "/src/main/resources/static/upload/img/", fileName);
            if (!writePictureTarget) {
                //上传文件失败
                return Result.error("上传项目文件失败");
            }
            //上传成功后，将可以访问的完整路径返回
            String fullImgPath = "/upload/img/" + fileName;
            return Result.ok().data(fullImgPath);
        } catch (Exception e) {
            log.error("上传项目文件失败", e);
            //上传图片失败
            return Result.error("上传项目文件失败");
        }
    }

    /**
     * oss上传文件
     *
     * @author <achao1441470436@gmail.com>
     * @since 2021/6/17 10:07
     */
    @GetMapping("oss")
    @ResponseBody
    public Map<String, Object> oss() {
        return ossService.getMark();
    }
}
